/**
 * Created by jiaoyumin on 2017/9/25.
 */
import axios from 'axios';
import {
  Message
} from 'element-ui';

const Axios = axios.create({
  timeout: 100000,
  withCredentials: true,
  headers: {
    'Content-Type': "application/json"
  }
});


//POST传参序列化（添加请求拦截器）
Axios.interceptors.request.use(
  config => {
    if (config.method === 'post') {
      config.data = JSON.stringify(config.data);
    }
    return config;
  },
  error => {
    Message({
      showClose: true,
      message: "参数错误",
      type: 'error'
    });
    return Promise.reject(error);
  }
);

//返回状态判断
Axios.interceptors.response.use(
  res => {
    if (res.data && res.data.errorCode > 0) {
      if (res.data.errorCode === 4000) {
        setTimeout(() => {
          window.location.href = res.data.url;
        }, 500)
      }else{  
        Message({
          //  饿了么的消息弹窗组件,类似toast
          message: res.data.errorMessage,
          type: "error"
        });
      }
      return Promise.resolve(res.data.errorMessage);
    }
    return res;
  },
  error => {
    return Promise.reject(error);
  }
);

export default {
  //fetchPost  请求方式
  fetchPost: function (url, params) {
    return new Promise((resolve, reject) => {
      Axios.post(url, params)
        .then(response => {
          if (response.data.errorCode) {
            if (response.data.errorCode === '0') {
              resolve(response.data)
            } else {
              Message({
                showClose: true,
                message: response.data.errorMessage,
                type: "warning"
              });
              reject(response);
            }
          } else {
            Message({
              showClose: true,
              message: "返回值错误！",
              type: "error"
            });
            reject(response);
          }
        }, err => {
          // console.log(err);
          reject(err);
        })
        .catch((error) => {
          reject(error)
        })
    })
  },


  //GET 请求方式
  fetchGet: function (url, params) {
    return new Promise((resolve, reject) => {
      Axios.get(url, {
          params: params
        })
        .then(response => {
          if (response.data.errorCode) {
            if (response.data.errorCode === '0') {
              resolve(response.data)
            } else {
              Message({
                showClose: true,
                message: response.data.errorMessage,
                type: "warning"
              });
              reject(response);
            }
          } else {
            Message({
              showClose: true,
              message: "返回值错误！",
              type: "error"
            });
            reject(response);
          }
        }, err => {
          reject(err);
        })
        .catch((error) => {
          reject(error)
        });
    })
  },
}
